<?php

namespace App\Repository\Service;

use App\Models\Service\ServiceLogsModel;
use App\Models\Service\ServiceModel;
use App\Repository\BaseRepository;

class ServiceLogsRepository extends BaseRepository
{
    public $model;
    public $log;

    public function __construct()
    {
        $this->model = new ServiceLogsModel();
//    $this->log = new Logger('anchor');
//    $this->log->pushHandler(
//      (new RotatingFileHandler(storage_path('/logs/anchor.log'), 14, Logger::DEBUG, true, 0777))->setFormatter(new LineFormatter(null, null, true, true))
//    );
        parent::__construct();
    }

    //列表
    public function index($request, $page = 1, $limit = 10)
    {
        $ModelAdminUsers = new \App\Models\Admin\AdminUsers();
        $AdminUsersTable = $ModelAdminUsers->getTable();
        $ServiceLogsTable = $this->model->getTable();
        //        查询条件
        $where = [];
        $where['where']['a.users_id'] = $request['user']['id'];
        $where['where']['a.service_id'] = $request['id'];
        $rows = [];
        $fields = ['a.created_at', 'a.remark'];
        $fields = array_merge($fields, ['b.nick_name']);
        foreach ($this->model->from($ServiceLogsTable, 'a')
                     ->leftJoin($AdminUsersTable . ' AS b', 'a.users_id', '=', 'b.id')
//                     ->leftJoin($OrdersUserTable . ' AS c', 'b.orders_user_id', '=', 'c.id')
                     ->select($fields)
                     ->searchWhere($where)
//                     ->page($page, $limit)
                     ->cursor() as $row) {
            $rows[] = $row;
        }
//        echo $this->getLastSql();
        return $this->returnMsg(200, '查询成功', $rows);
    }

//记录
    public function add($request)
    {
        $serviceId = intval($request->get('id'));
        $ModelService = new ServiceModel();
        $row = $ModelService->where(['id' => $serviceId])->first();
//        echo $this->getLastSql();
        if (empty($row)) {
            return $this->returnMsg(2, '数据异常');
        }
//        如果今天没有记录过跟进,那么就要记录天数
        $days = $row['days'];
        if ($this->model->where([['id', '=', $serviceId], ['created_at', '>=', date('Y-m-d')]])->count('id') <= 0) {
            $days = $days + 1;
        }
//        保存信息
        $inData = [
            'service_id' => $serviceId,
            'orders_id' => $row['orders_id'],
            'users_id' => $row['users_id'],
            'remark' => $request->get('remark')
        ];
        if ($this->model->insert($inData)) {
//        更新原客服数据
            $upData = [
                'updated_at' => date('Y-m-d H:i:s'),
                'nums' => $row['nums'] + 1,
                'days' => $days
            ];
            if (false !== $ModelService->where(['id' => $serviceId])->update($upData)) {
                return $this->returnMsg(200, '跟进已记录');
            }
            return $this->returnMsg(2, '跟进记录失败');
        }
        return $this->returnMsg(2, '跟进信息保存失败');
    }
}
